package cn.dceast.former.service;

import cn.dceast.algorithm.dao.EyeAiLibraryMapper;
import cn.dceast.common.utils.ShellUtils;
import cn.dceast.former.dao.EyeModelCommentMapper;
import cn.dceast.former.dao.EyeShowResultMapper;
import cn.dceast.former.model.EyeModelComment;
import com.google.gson.Gson;
import com.jcraft.jsch.JSchException;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.*;

/**
 * Created by fanbo on 2017-07-18.
 * 模型评价服务
 */
@Service
public class EyeShowResultService {

    @Autowired
    private EyeShowResultMapper eyeShowResultMapper;
    @Autowired
    private EyeAiLibraryMapper eyeAiLibraryMapper;

    /*获取数据清单*/
    public void getDataList(Map<String, Object> params) {
        //根据modelId获取算法设置字段
        String algorithm = (String) eyeShowResultMapper.getAlgo((Integer) params.get("modelId")).get("model_algorithm");
        //根据tableName查询所有数据
        List<Map> dataList = eyeShowResultMapper.getListByTableName((String) params.get("tableName"));
        //格式化dataList
        List<String> rightList = changeData(dataList);
        //生成txt文件
        String filePath = createTxtFile(rightList);
        //上传文件到Linux系统null，返回上传后的路径
        String desPath = uploadLinux(filePath, "/user/data/" + (String) params.get("tableName") + UUID.randomUUID().toString() + ".txt");
        //执行算法
        String[] algoArr = algorithm.split(",");
        Map algoInfo = null;
        // 更新结果表的状态为进行中1
        params.put("state", 1);
        eyeShowResultMapper.updateState(params);
        String algoId = "";
        Map<String,Object> aiArgs = new HashedMap();
        Gson gson = new Gson();
        //循环执行算法
        for (int i = 0; i < algoArr.length; i++) {
            algoInfo = eyeShowResultMapper.getAlgoInfo(Integer.valueOf(algoArr[i]));
            algoId = algoInfo.get("id").toString();
            aiArgs.put("modelId",params.get("modelId"));
            aiArgs.put("aiId",algoId);
            aiArgs.put("userId",params.get("userid"));
            Map<String,Object> aiMap=eyeAiLibraryMapper.getAiArgmap(aiArgs);
            //// TODO: 2017/8/1  算法参数
            String AiArgs = " ";
            if (aiMap!=null){
                String aiMapArgsStr = aiMap.get("aiArgs").toString();
                Map<String,String> aiMapArgs = gson.fromJson(aiMapArgsStr,Map.class);
                for (String k:aiMapArgs.keySet()){
                    AiArgs+=aiMapArgs.get(k)+" ";
                }
            }
            //// TODO: 2017/8/1  增加表名参数
            String K_MeansMllib = algoInfo.get("ai_class") + " " + algoInfo.get("url") + algoInfo.get("jar") + " " + "file://" + desPath + " " + (Integer) params.get("userid") + " " + (String) params.get("tableName") + "result" + UUID.randomUUID().toString() + ".txt" + " " + (Integer) params.get("modelId") + " " + Integer.valueOf(algoArr[i]) + " " + Integer.valueOf(algoArr[i]) + " " + "http://eagleye2.eastdc.cn:85/eyeShowResultController/getResult.do " + (String) params.get("tableName");//+algoSetting.get(algoArr[i])
            if(!StringUtils.isEmpty(AiArgs.trim())){
                K_MeansMllib+=AiArgs;
            }
            System.out.println(K_MeansMllib);
            ShellUtils.mkShell(K_MeansMllib);
        }
    }

    private String uploadLinux(String filePath, String desPath) {
        try {
            //连接服务器
            ShellUtils.connect("root", "4U5g1ZO7jas8Y", "122.114.147.132");
            ShellUtils.uploadFile(filePath, desPath);
            return desPath;
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<String> changeData(List<Map> dataList) {
        List<String> rightList = new ArrayList<>();
        String array = "";
        for (int i = 1; i < dataList.size(); i++) {
            array = "";
          /*  if(i==0){
                String head = "";
                Iterator iter = dataList.get(i).entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    Object key = entry.getKey();
                    head += key+"  ";
                }
                rightList.add(head);
            }*/
            Iterator iter = dataList.get(i).entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if (!entry.getKey().equals("id") && !entry.getKey().equals("state") && !entry.getKey().equals("res1") && !entry.getKey().equals("res2") && !entry.getKey().equals("res3")) {
                    Object value = entry.getValue();
                    array += value + "  ";
                }
            }
            //// TODO: 2017/8/1 处理id去除，这一列
            rightList.add(array);
        }
        return rightList;
    }

    private String createTxtFile(List<String> dataList) {
        FileWriter writer = null;
        try {
            File file = ResourceUtils.getFile("data.txt");
            System.out.println(file.exists() + "-----");
            if (!file.exists()) {
                file.createNewFile();
            }
            writer = new FileWriter(file);
            for (int i = 0; i < dataList.size(); i++) {
                writer.write(dataList.get(i).toString() + "\r\n");
            }
            System.out.print(file.getAbsolutePath() + "=========================");
            writer.flush();
            writer.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List getValueList(Map<String, Object> params) {
        //获取表字段
        List<Map> list = eyeShowResultMapper.getValueList(params);
        List<Map> valueList = eyeShowResultMapper.getFirstList(params);
        List<Map> resultList = new ArrayList<>();
        // TODO: 2017/8/2 获取第一条记录 组成对应关系
        for (int i = 0; i < list.size(); i++) {
            Map map = new HashMap();
            String Field = (String) list.get(i).get("Field");
            if (!Field.equals("id") && !Field.equals("state") && !Field.equals("res2") && !Field.equals("res3")) {
                map.put("Field", Field);
                map.put("value", valueList.get(0).get(Field));
                resultList.add(map);
            }
        }
        return resultList;
    }

    public void getResult(String path, Integer userid, String tableName) {
        Map params = new HashMap();
        //读取Hdfs数据到resultPath路径上面
        String resultPath = ShellUtils.readResult(path, userid);
        //读取txt文件并存到List
        List resultList = readTxt(resultPath);
        //读取原始数据，循环插入数据
        List<Map> dataList = eyeShowResultMapper.selectAll(tableName);
        int updatecount = 0;
        for (int i = 0; i < dataList.size() - 1; i++) {
            params.put("tableName", tableName);
            params.put("rownum", i + 2);
            params.put("result_value", resultList.get(i));
            updatecount = eyeShowResultMapper.updateInfo(params);
        }
    }

    public List readTxt(String resultPath) {
        List<String> list = new LinkedList<String>();
        try {
            String encoding = "UTF-8";
            File file = new File(resultPath);
            String lineinfo = "";
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
                BufferedReader bufferReader = new BufferedReader(read);
                while ((lineinfo = bufferReader.readLine()) != null) {
                    list.add(lineinfo);
                }
                read.close();
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return list;
    }

    public int updateState(Map params) {
        int count = eyeShowResultMapper.updateState(params);
        return count;
    }

    public List<Map> getState(Map<String, Object> params) {
        List<Map> list = eyeShowResultMapper.getState(params);
        List<Map> resultList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map map = new TreeMap();
            Iterator iter = list.get(i).entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if (!entry.getKey().equals("id") && !entry.getKey().equals("state") && !entry.getKey().equals("res2") && !entry.getKey().equals("res3")) {
                    Object value = entry.getValue();
                    map.put(entry.getKey(), entry.getValue());
                }
            }
            resultList.add(map);
        }
        return resultList;
    }
}
